package com.qiahao.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qiahao.dto.PageDTO;
import com.qiahao.bean.Question;
import com.qiahao.constant.VoiceResult;
import com.qiahao.mapper.QuestionMapper;
import com.qiahao.service.QuestionService;
import com.qiahao.service.VoiceService;
import com.qiahao.util.Utils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

@Service
@Transactional
public class QuestionServiceImpl implements QuestionService {

    @Autowired
    QuestionMapper questionMapper;

    @Autowired
    VoiceService voiceService;

    @Override
    public Map<String, Object> addQuestion(Question question) {
        Map<String, Object> map = new HashMap<>();
        String msg = "";

        if (StringUtils.isEmpty(question.getQuestion())) {
            msg = "请输入问题内容";
        }

        if (questionMapper.findPhoneByQuestionName(question.getQuestion()) != null) {
            msg = "问题已存在,不能重复添加";
        }

        if (StringUtils.isEmpty(msg)) {
            Map<String,Object> voiceMap = voiceService.getVoice(question);
            msg = voiceMap.get("error")+"";
            if (StringUtils.isEmpty(msg)) {
                questionMapper.AddQuestion(question);
                String fileName = System.currentTimeMillis() +"id"+question.getId()+ ".mp3";
                try {
                    Utils.saveFile(question.getPath(), fileName, voiceMap.get("speech").toString());
                    question.setPath("voice/" + fileName);
                    questionMapper.updateQuestionPath(question.getPath(),question.getId());
                    msg = "添加成功";
                } catch (Exception e) {
                    e.printStackTrace();
                    msg = "文件保存失败";
                }

            }

        }
        map.put("msg", msg);
        return map;
    }

    @Override
    public PageDTO<Question> findAllQuestion(int pageNo, int pageSize) {
        PageDTO<Question> dto = new PageDTO();
        Page<Question> page = PageHelper.startPage(pageNo, pageSize);
        dto.setData(questionMapper.getAllQuestion());
        dto.setTotalCount(page.getTotal());
        dto.setPageNo(pageNo);
        dto.setTotalPage(page.getPages());
        return dto;
    }

    @Override
    public Question findQuestionByQuestionName(String question) {
        return questionMapper.findPhoneByQuestionName(question);
    }

    @Override
    public String getQuestionResult(File file, Long questionId) {
//        filePath = filePath.replace("-","/");

        String base64VoiceStr = Utils.getFileStr(file);
        if (StringUtils.isEmpty(base64VoiceStr)) {
            return VoiceResult.OTHER;
        }

        Map<String, Object> map = voiceService.voice2Text(base64VoiceStr);
        String error = (String) map.get("error");
        if (StringUtils.isEmpty(error)) {
            return compareResult((String) map.get("result"), questionId);
        } else {
            return VoiceResult.OTHER;
        }

    }


    /**
     * 结果对比
     *
     * @param result
     * @param questionId
     */
    private String compareResult(String result, Long questionId) {

        Question question = questionMapper.findPhoneByQuestionId(questionId);
        if (question == null) {
            return VoiceResult.OTHER;
        }

        String[] errorResult = question.getErrorAnswer().split(",");
        String[] correctResult = question.getCorrectAnswer().split(",");




        //错误答案匹配成功
        if (checkResult(errorResult, result)) {
            return VoiceResult.NO;
        }


        //正确答案比对成功
        if (checkResult(correctResult, result)) {
            return VoiceResult.YES;
        }

        return VoiceResult.OTHER;


    }

    /**
     * 将问题答案与语音文字进行对比
     * 0代表未匹配到
     * 1代表匹配成功
     */
    private boolean checkResult(String[] result, String voiceText) {
        System.out.print("voiceText"+voiceText);
        boolean checkResult = false;

        for (int i = 0; i < result.length; i++) {

            if (voiceText.contains(result[i])) {
                checkResult = true;
                break;
            }

        }
        return checkResult;

    }
}
